package com.alading.gateway.filter;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 路由限流配置
 * @author dzg
 * @date 2020-11-05
 */
@Configuration
public class RateLimiterConfig {

    /**
     * IP限流
     * @return
     */
    @Bean(value = "remoteAddrKeyResolver")
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

//    /**
//     * 用户限流，使用这种方式限流，请求路径中必须携带userId参数
//     * @return
//     */
//    @Bean(value = "userKeyResolver")
//    KeyResolver userKeyResolver() {
//        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("userId")));
//    }
//
//    /**
//     * 接口限流，获取请求地址的uri作为限流key
//     */
//    @Bean(value = "apiKeyResolver")
//    KeyResolver apiKeyResolver() {
//        return exchange -> Mono.just(exchange.getRequest().getPath().value());
//    }
}
